use axum::{routing::{post, get}, Router};
use serde::Deserialize;

use crate::{error::AppErr, server::{req::{device::DeviceInfo, handler::MessageHandler}, res::Void, Cbor}, store::adv_cfg::{self, TbAdvCfg}};

#[derive(Debug, Deserialize)]
struct CreateReq {
    adv_id: u64,
    play_start: u32,
    play_end: u32,
    position: u8,
    duration: u32,
}

async fn on_create(device_info: DeviceInfo, req: Cbor<CreateReq>) -> Result<Cbor<u64>, AppErr> {
    let id = adv_cfg::create(
        device_info.id, 
        req.adv_id, 
        req.position, 
        req.play_start, 
        req.play_end, 
        req.duration
    ).await?;
    Ok(Cbor(id))
}

async fn on_query(device_info: DeviceInfo) -> Result<Cbor<Box<[TbAdvCfg]>>, AppErr> {
    let res = adv_cfg::query(device_info.id).await?;
    Ok(Cbor(res))
}

async fn on_delete(id: Cbor<u64>) -> Result<Void, AppErr> {
    adv_cfg::delete(id.0).await?;
    Ok(Void)
}

async fn on_notify(h: MessageHandler) -> Result<Void, AppErr> {
    h.notify_adv().await?;
    Ok(Void)
}

pub fn register() -> Router {
    Router::new()
        .route("/create", post(on_create))
        .route("/query_all", get(on_query))
        .route("/delete", post(on_delete))
        .route("/notify", get(on_notify))
}

